package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"vehicle-mgmt-sys/cache"
	"vehicle-mgmt-sys/models"
)

func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		*
		FROM
		roles
		LEFT JOIN user_roles ON user_roles.rid = roles.id
		WHERE user_roles.uid=1
	*/

	var role []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid=?", uid).
		Debug().
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}

func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		*
		FROM
		nodes
		LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE role_nodes.rid = 1
	*/

	var node []models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid = ?", rid).
		Debug().
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
	return
}

func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	data := models.UserRole{
		Uid: uid,
		Rid: rid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var user []models.User
	redis_key := "user_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("users").Offset(offset).Limit(size).Find(&user).Debug()
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	var count int64
	models.DB.Model(&models.User{}).Count(&count)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"user":  user,
		},
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var user models.User
	redis_key := "user_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("users").First(&user).Debug()
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return

}

func Add(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	data := models.User{
		Username: username,
		Password: password,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func CarAdd(c *gin.Context) {
	carNo := c.PostForm("car_no")
	carName := c.PostForm("car_name")
	carCode := c.PostForm("car_code")

	if carNo == "" || carName == "" || carCode == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	car := models.Car{
		CarNo:   carNo,
		CarName: carName,
		CarCode: carCode,
	}

	err := models.DB.Create(&car).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func CarOrderAdd(c *gin.Context) {
	carNo := c.PostForm("car_no")
	carName := c.PostForm("car_name")
	carCode := c.PostForm("car_code")
	orderNo := c.PostForm("order_no")
	orderName := c.PostForm("order_name")
	orderPrice, _ := strconv.Atoi(c.PostForm("order_price"))

	if carNo == "" || carName == "" || carCode == "" || orderNo == "" || orderName == "" || orderPrice == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	data := models.CarOrder{
		CarNo:      carNo,
		CarName:    carName,
		CarCode:    carCode,
		OrderNo:    orderNo,
		OrderName:  orderName,
		OrderPrice: orderPrice,
	}

	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	/*
		SELECT
		  orders.cid as OrderId,
		  cars.car_no as CarNo,
		  cars.car_name as CarName,
		  cars.car_code as CarCode,
		  orders.order_no as OrderNo,
		  orders.order_name as OrderName,
		  orders.order_price as OrderPrice
		FROM
		  orders
		  LEFT JOIN cars ON cars.id = orders.cid
	*/

	var order []models.CarOrder

	redis_key := "order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select(
				"orders.cid as OrderId",
				"cars.car_no as CarNo",
				"cars.car_name as CarName",
				"cars.car_code as CarCode",
				"orders.order_no as OrderNo",
				"orders.order_name as OrderName",
				"orders.order_price as OrderPrice").
			Joins("LEFT JOIN cars ON cars.id = orders.cid").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}

	var count int64
	models.DB.Model(&models.Order{}).Count(&count)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"order": order,
		},
	})
	return
}

func CarOrderDetail(c *gin.Context) {
	id := c.Query("id")

	var order models.CarOrder

	redis_key := "order_list" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select(
				"orders.cid as OrderId",
				"cars.car_no as CarNo",
				"cars.car_name as CarName",
				"cars.car_code as CarCode",
				"orders.order_no as OrderNo",
				"orders.order_name as OrderName",
				"orders.order_price as OrderPrice").
			Joins("LEFT JOIN cars ON cars.id = orders.cid").
			Where("orders.id = ?", id).
			Debug().
			Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	})
	return
}
